package com.shuai.blog.controller;

import com.shuai.blog.common.HttpResult;
import com.shuai.blog.common.UserSessionUtils;
import com.shuai.blog.entity.CommentInfo;
import com.shuai.blog.entity.UserInfo;
import com.shuai.blog.entity.vo.CommentVO;
import com.shuai.blog.service.CommentService;
import com.shuai.blog.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;

    @RequestMapping("/list")
    public HttpResult commentsList(Integer artId) {
        if (artId == null) {
            return HttpResult.fail(-1, "非法参数");
        }
        List<CommentInfo> commentsList = commentService.commentsList(artId);
        List<CommentVO> commentVOs = new ArrayList<>();
        for (CommentInfo commentInfo : commentsList) {
            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(commentInfo, commentVO);
            commentVO.setNickname(userService.getUserById(commentVO.getUserId()).getNickname());
            commentVOs.add(commentVO);
        }
        return HttpResult.success(commentVOs);
    }


    @RequestMapping("/add")
    public HttpResult addComment(CommentInfo commentInfo, HttpServletRequest request) {
        if (commentInfo == null ||
                commentInfo.getArtId() == null ||
                !StringUtils.hasLength(commentInfo.getContent())) {
            return HttpResult.fail(-1, "非法参数");
        }
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "非法请求");
        }
        commentInfo.setUserId(userInfo.getUserId());
        return HttpResult.success(commentService.addComment(commentInfo));
    }

}
